/* Training file to see how the MPI_Send and MPI_Recv function worked*/

#include <stdio.h>
#include <mpi.h>
#define send_data_tag 2001
#define return_data_tag 2002
#define ARRAY_LEN 100
#define MY_LEN 25


main(int argc, char **argv) 
{
   int array[ARRAY_LEN]={0},rcarray[25]={0};
   int i, sum, my_sum;
   int my_id, root_process, ierr, num_procs;
   int n, my_n;
   MPI_Status status;
   
   
   

   /* Now replicate this process to create parallel processes.  */
   ierr = MPI_Init(&argc, &argv);
   
   
   root_process = 0;

   /* find out MY process ID, and how many processes were started */
   ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
   ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

   if(my_id == root_process)
   {
      // construction de la matrice
      for (i=0;i<ARRAY_LEN;i++)
      {
         array[i] = i;
      }
      
      n = ARRAY_LEN;
      my_n =  MY_LEN;
      
      for (i=1;i<num_procs;i++)
      {
         
         ierr = MPI_Send( &my_n, 1, MPI_INT,
            i, send_data_tag, MPI_COMM_WORLD);
            
         
      }
      
   }
   
   else
   {
      ierr = MPI_Recv( &my_n, 1, MPI_INT,
            root_process, send_data_tag, MPI_COMM_WORLD, &status);
   }
   
   MPI_Scatter(array,MY_LEN, MPI_INT,rcarray,MY_LEN,MPI_INT,root_process,MPI_COMM_WORLD);
   
   printf("Process %i received array beginning with : %i \n",my_id,rcarray[0]);
   
   my_sum=0;
   for (i=0;i<my_n;i++)
   {
      my_sum += rcarray[i];
   }
   
   printf("%i Sending sum of %i \n",my_id,my_sum);
   sum = 0;
   MPI_Reduce(&my_sum, &sum,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
   
   if(my_id == root_process)
   {
      printf("!!!!!!!!!Final sum is : %i !!!!!!!!!!\n",sum);
   }
   
   
   /* Stop this process */

   ierr = MPI_Finalize();
}














   

